/**
 * Copyright (c) 2016-2022 控议网络 All rights reserved.
 *
 * http://www.kongyw.com
 *
 * 版权所有，侵权必究！
 */

package com.basic.framework.interceptor;


import com.basic.app.exception.BizException;
import com.basic.app.response.AppResponseCode;
import com.basic.app.util.JwtUtils;
import com.basic.framework.annotation.Login;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtils jwtUtils;

    public static final String USER_KEY = "memberId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if(StringUtils.isBlank(token)){
            token = request.getParameter(jwtUtils.getHeader());
        }

        //凭证为空
        if(StringUtils.isBlank(token)){
            throw new BizException(AppResponseCode.CODE_ERROR_TOKEN.getMsg(), AppResponseCode.CODE_ERROR_TOKEN.getCode());
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if(claims == null){
            //token非法
            throw new BizException(AppResponseCode.CODE_ERROR_LOGIN_TIMEOUT.getMsg(), AppResponseCode.CODE_ERROR_LOGIN_TIMEOUT.getCode());
        }
        if(jwtUtils.isTokenExpired(claims.getExpiration())){
            //token过期
            throw new BizException(AppResponseCode.CODE_ERROR_LOGIN_TIMEOUT.getMsg(), AppResponseCode.CODE_ERROR_LOGIN_TIMEOUT.getCode());
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, Long.parseLong(claims.getSubject()));

        return true;
    }
}
